<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('标题')" prop="title">
            <el-input
              v-model="form.title"
              :placeholder="$t('标题')"
              show-word-limit
              maxlength="200"
              :readonly="form.status === 'N' ? false : 'readonly'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('公告内容')" prop="content">
            <EditorTxt v-model="form.content" :height="400" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('发布时间')" prop="releaseTime">
            <el-date-picker
              v-model="form.releaseTime"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('发布时间')"
              :readonly="form.status === 'N' ? false : 'readonly'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('发布人')" prop="releaseUser">
            <UserSelect v-model="form.releaseUser" :placeholder="$t('发布人')" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="form.status === 'N'" :label="$t('通知方式')" prop="methodInforme">
            <el-checkbox-group v-model="form.methodInforme">
              <el-checkbox
                v-for="(dict, index) in methodInformeOptions"
                :key="index"
                :label="dict.dictValue"
                border
                style="zoom: 90%;"
              >{{ $t(dict.dictLabel) }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="form.status === 'N'" :label="$t('是否通知全员')" prop="informAll">
            <el-radio-group v-model="form.informAll" @change="informAllYesNoOptions">
              <el-radio
                v-for="dict in yesNoOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            v-if="form.informAll === 'N' && form.status !== 'Y'"
            ref="Role"
            :label="$t('接收角色')"
            prop="receiveRole"
          >
            <el-select v-model="form.receiveRole" filterable multiple :placeholder="$t('请选择')">
              <el-option
                v-for="item in roleOptions"
                :key="item.roleId"
                :label="$t(item.roleName)"
                :value="item.roleId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            v-if="form.informAll === 'N' && form.status !== 'Y'"
            ref="Post"
            :label="$t('接收岗位')"
            prop="receivePost"
          >
            <el-select v-model="form.receivePost" filterable multiple :placeholder="$t('请选择')">
              <el-option
                v-for="item in postOptions"
                :key="item.postId"
                :label="item.postName"
                :value="item.postId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            v-if="form.informAll === 'N' && form.status !== 'Y'"
            ref="Dept"
            :label="$t('接收部门')"
            prop="receiveDept"
          >
            <DeptSelect v-model="form.receiveDept" filterable multiple :placeholder="$t('请选择')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            v-if="form.informAll === 'N' && form.status !== 'Y'"
            ref="User"
            :label="$t('接收用户')"
            prop="receiveUser"
          >
            <UserSelect v-model="form.receiveUser" filterable multiple :placeholder="$t('接收用户')" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div v-if="form.status === 'N'" slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存 取消按钮-->
      <save-btn has-permi="msg:send" />
      <el-button
        type="primary"
        @click="handleSend"
      >保存并发送
      </el-button>
    </div>
    <div v-if="form.status === 'Y'" slot="footer" class="dialog-footer" style="text-align: right;">
      <el-button
        type="primary"
        @click="cancel"
      >关闭
      </el-button>
    </div>
  </div>
</template>
<script>
import { saveMsgSend, getMsgSend } from '@/api/system/message/msgSend'
import { allRole } from '@/api/system/role'
import EditorTxt from '@/components/Editor'
import { listPost } from '@/api/system/post'

export default {
  components: {
    EditorTxt
  },
  data() {
    // 非通知全员时验证 接收角色，接收岗位，接收部门，接收用户，四个至少填写一个
    const conditiOnvalidate = (rule, value, callback) => {
      if (this.form.receiveRole.length === 0 && this.form.receivePost.length === 0 && this.form.receiveDept.length === 0 && this.form.receiveUser.length === 0) {
        callback(new Error('请至少填写一项'))
      } else {
        // 任意值被填写，清除验证提示
        if (this.form.receiveRole.length > 0 || this.form.receivePost.length > 0 || this.form.receiveDept.length > 0 || this.form.receiveUser.length > 0) {
          this.$refs.Role.clearValidate()
          this.$refs.Post.clearValidate()
          this.$refs.Dept.clearValidate()
          this.$refs.User.clearValidate()
        }
        callback()
      }
    }
    return {
      // 表单参数
      form: {
        methodInforme: [],
        receiveRole: [],
        receivePost: [],
        receiveDept: [],
        receiveUser: []
      },
      // 【通知】表格数据
      msgSendSituationList: [],
      situationForm: {},
      // 遮罩层
      loading: false,
      sendSituationLoading: false,
      // 是否 y/n 按钮
      yesNoOptions: [],
      statusOptions: [],
      // 角色选项
      roleOptions: [],
      // 岗位选项
      postOptions: [],
      // 通知方式字典
      methodInformeOptions: [], // 表单参数
      // 查询参数
      queryParams: {
        user: {
          userId: undefined
        },
        title: undefined,
        nickName: undefined,
        pageNum: 1,
        pageSize: 10
      },
      // 表单校验
      rules: {
        title: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        content: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        releaseTime: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        releaseUser: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        methodInforme: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        informAll: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        receiveRole: [
          { required: false, validator: conditiOnvalidate, trigger: 'change' }
        ],
        receivePost: [
          { required: false, validator: conditiOnvalidate, trigger: 'change' }
        ],
        receiveDept: [
          { required: false, validator: conditiOnvalidate, trigger: 'change' }
        ],
        receiveUser: [
          { required: false, validator: conditiOnvalidate, trigger: 'change' }
        ]

      }
    }
  },
  created() {
    // 是否 字典sys_yes_no字典翻译
    this.getDicts('sys_yes_no').then(response => {
      this.yesNoOptions = response.data
      this.statusOptions = response.data
    })
    // 通知方式 msg_send_type字典翻译
    this.getDicts('msg_send_type').then(response => {
      this.methodInformeOptions = response.data
    })
    // 查询角色
    allRole().then(response => {
      this.roleOptions = response.data
    })
    // 查询岗位
    listPost({}).then(response => {
      this.postOptions = response.rows
      this.loading = false
    })
  },
  methods: {
    // 初始化数据
    init(data) {
      this.loading = true
// debugger
      if (data != null && data.id !== undefined) {
        getMsgSend(data.id).then(response => {
          this.form = response.data
          this.loading = false
        })
      } else {
        this.reset()
        this.loading = false
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,

        title: undefined,

        content: undefined,

        releaseTime: new Date(),

        releaseUser: this.$store.state.user.userId,

        methodInforme: [],

        informAll: 'Y',

        receiveRole: [],

        receivePost: [],

        receiveDept: [],

        receiveUser: [],

        createBy: undefined,

        createTime: undefined,

        updateBy: undefined,

        updateTime: undefined,

        delFlag: undefined,

        status: 'N'

      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    // 保存按钮
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true
          saveMsgSend(this.form).then(response => {
            if (response.code === 200) {
              if (this.form.status === 'Y') {
                this.msgSuccess(this.$t('发送成功'))
                this.closeForm()
              } else {
                this.msgSuccess(this.$t('保存成功'))
                this.closeForm()
              }
            } else {
              this.msgError(response.msg)
            }
            this.loading = false
          })
        } else {
          this.locationError(document)
        }
      })
    },

    // 如果通知全员情况下 接受角色，接收岗位，接收部门，接收用户表单重置
    informAllYesNoOptions(value) {
      if (value === 'Y') {
        this.form.receiveRole = []
        this.form.receivePost = []
        this.form.receiveDept = []
        this.form.receiveUser = []
      }
    },
    // 发送
    handleSend() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.form.status = 'Y'
          this.submitForm()
        } else {
          this.locationError(document)
        }
      })
    },
    // 通知状态字典翻译
    statusFormat(row) {
      return this.selectDictLabels(this.statusOptions, row.status)
    }
  }
}
</script>
